package com.example.service.impl;

import com.example.dto.CheckItemReport;
import com.example.dto.OrdersDto;
import com.example.dto.OrdersListDto;
import com.example.dto.ReportListDto;
import com.example.mapper.CireportMapper;
import com.example.mapper.DoctorMapper;
import com.example.mapper.OrdersMapper;
import com.example.pojo.*;
import com.example.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrderService {
    @Autowired
    private UserService userService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private CireportMapper checkItemReportMapper;
    @Autowired
    private DoctorService doctorService;

    @Override
    public ResponseEntity<Map<String, Object>> getOrder(OrdersDto orders) {
        User user =userService.selectOrderByUserId(orders.getUserId());
        Hospital hospital = hospitalService.getHospitalById(orders.getHpId());
        Setmeal setmeal = setmealService.getSetmealById(orders.getSmId());
//        Doctor doctor =doctorService.selectDoctorBydocId(orders.getDocId());// 新增的医生信息
        if (user != null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "success");
            response.put("user", user);
            response.put("date", orders.getOrderDate());
//            response.put("doctor", doctor);//新增的医生信息
            response.put("hospital", hospital);
            response.put("setmeal", setmeal);
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "fail");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    @Override
    public ResponseEntity<Map<String, Object>> confirmOrder(@RequestBody OrdersDto ordersDto) {
        User user = userService.selectOrderByUserId(ordersDto.getUserId());
        Hospital hospital = hospitalService.getHospitalById(ordersDto.getHpId());
        Setmeal setmeal = setmealService.getSetmealById(ordersDto.getSmId());
        Doctor doctor = doctorService.selectDoctorByDocId(ordersDto.getDocId()); // 注意方法名要与接口一致

        if (user != null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "success");
            response.put("user", user);
            response.put("date", ordersDto.getOrderDate());
            response.put("doctor", doctor); // 将医生信息添加到返回数据中
            response.put("hospital", hospital);
            response.put("setmeal", setmeal);
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "fail");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    @Override
    public ResponseEntity<Map<String, Object>> insertOrder(OrdersDto ordersDto) {
        // Create Orders object and set properties
        Orders orders = new Orders();
        orders.setOrderDate(ordersDto.getOrderDate());
        orders.setUserId(ordersDto.getUserId());
        orders.setHpId(ordersDto.getHpId());
        orders.setSmId(ordersDto.getSmId());
        orders.setDocId(ordersDto.getDocId()); // 设置 docId
        orders.setState(1); // 设置默认状态为1

        // Insert the order
        int rowsAffected = ordersMapper.insertOrder(orders);

        // Handle response based on insert result
        if (rowsAffected > 0) {
            // Retrieve the inserted orderId from the Orders object
            Integer insertedOrderId = orders.getOrderId();

            // Retrieve the inserted order details using orderId
            Orders insertedOrder = ordersMapper.getOrderById(insertedOrderId);

            // 查询所有检查项目ID
            List<Integer> ciIds = checkItemReportMapper.findCheckItemIdsBySetMealId(ordersDto.getSmId());

            for (Integer ciId : ciIds) {
                // 获取检查项目名称
                String ciName = checkItemReportMapper.findCheckItemNameById(ciId);

                // 创建并保存检查报告记录
                CheckItemReport checkItemReport = new CheckItemReport();
                checkItemReport.setCiId(ciId);
                checkItemReport.setCiName(ciName);
                checkItemReport.setOrderId(orders.getOrderId());
                checkItemReportMapper.insertCheckItemReport(checkItemReport);
            }
            // Prepare response map
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "success");
            response.put("orderId", insertedOrderId); // Add orderId to response
            response.put("orders", insertedOrder); // Optionally add other details
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "fail");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }


    @Override
    public List<OrdersListDto> getOrdersByUserId(String userId) {
        return  ordersMapper.getOrdersByUserId(userId);
    }


    @Override
    public void cancelOrder(Integer orderId) {
        ordersMapper.updateOrderStateToCancelled(orderId);
    }

    @Override
    public boolean checkOrderExists(Integer orderId) {
        // Implement logic to check if orderId exists in the database
        return ordersMapper.exists(orderId) > 0; // Check if orderId exists
    }


}
